package cn.fl.repay.controller;

import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.api.IMcrBillOfflineSettleApiService;
import cn.fl.capital.condition.CapFundQueryCondition;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.dto.McrBillOfflineSettleDTO;
import cn.fl.capital.service.ICapFundService;
import cn.fl.capital.vo.CapFundVO;
import cn.fl.commons.result.ResponseData;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.repay.condition.InsOfflineFundDtlQueryCondition;
import cn.fl.repay.condition.InsOfflineRepayDtlQueryCondition;
import cn.fl.repay.constant.RepayConstant;
import cn.fl.repay.service.IInsOfflineFundDtlService;
import cn.fl.repay.service.IInsOfflineRepayDtlService;
import cn.fl.repay.service.IInsOfflineRepayLogService;
import cn.fl.repay.vo.InsOfflineFundDtlVO;
import cn.fl.repay.vo.InsOfflineRepayDtlVO;
import cn.fl.repay.vo.InsOfflineRepayLogVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysDictionaryService;
import cn.lionbridgecapital.loan.model.condition.McrBillMQC;
import cn.lionbridgecapital.loan.model.dto.McrBillMDTO;
import cn.lionbridgecapital.loan.service.api.IMcrBillMApiService;
import cn.lionbridgecapital.loan.service.api.IYiLlionApiService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shiqiao.fl.repay.order.facade.ICapRepayCallbackApiService;
import com.shiqiao.fl.repay.order.request.OfflineDecomposeParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import pay.business.facade.custpay.api.ICmmRechargeRecordApiService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 线下还款申请资金明细 控制层
 */
@Controller
@RequestMapping("/repay/insOfflineFundDtl")
public class InsOfflineFundDtlController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(cn.fl.repay.controller.InsOfflineFundDtlController.class);

	/**
	 * InsOfflineFundDtl 服务层BEAN
	 */
	@Autowired
	private IInsOfflineFundDtlService insOfflineFundDtlService;
	@Autowired
	private IInsOfflineRepayLogService insOfflineRepayLogService;
	@Autowired
	private IInsOfflineRepayDtlService insOfflineRepayDtlService;
	@Autowired
	private ICapFundService capFundService;
	@Autowired
	private ISysDictionaryService sysDictionaryService;
	@Autowired
	private ICmmRechargeRecordApiService cmmRechargeRecordApiService;
	@Autowired
	private IYiLlionApiService yiLlionApiService;
	@Autowired
	private IMcrBillOfflineSettleApiService mcrBillOfflineSettleApiService;
	@Autowired
	private IMcrBillMApiService mcrBillMApiService;
	@Autowired
	private ICapRepayCallbackApiService capRepayCallbackApiService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载InsOfflineFundDtl列表页面.", CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("repay/insOfflineFundDtl/insOfflineFundDtlList");

		String id = request.getParameter("id");
		InsOfflineRepayLogVO insOfflineRepayLogVO = this.insOfflineRepayLogService.selectById(Long.valueOf(id));
		mav.addObject("insOfflineRepayLogVO", insOfflineRepayLogVO);

		List<KeyValueVO> applyStsCdList = this.sysDictionaryService.getKvList(RepayConstant.APPLY_STS_CD, CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());
		mav.addObject("applyStsCdList", applyStsCdList);
		return mav;
	}
	
	/**
	 * 到新增页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toAddPage", "加载InsOfflineFundDtl Add页面.", CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("repay/insOfflineFundDtl/insOfflineFundDtlModify");

		String id = request.getParameter("id");
		InsOfflineRepayLogVO insOfflineRepayLogVO = this.insOfflineRepayLogService.selectById(Long.valueOf(id));
		mav.addObject("insOfflineRepayLogVO", insOfflineRepayLogVO);

		List<KeyValueVO> applyStsCdList = this.sysDictionaryService.getKvList(RepayConstant.APPLY_STS_CD, CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());
		mav.addObject("applyStsCdList", JSON.toJSONString(applyStsCdList));
		//this.prepare(request,mav);
		return mav;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toModifyPage", "加载InsOfflineFundDtl Modify页面.", CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("repay/insOfflineFundDtl/insOfflineFundDtlModify");
		//this.prepare(request,mav);
		
		String id=request.getParameter("id");
		InsOfflineFundDtlVO insOfflineFundDtlVO = this.insOfflineFundDtlService.selectById(Long.valueOf(id));
        mav.addObject("insOfflineFundDtlVO", insOfflineFundDtlVO);
		return mav;
	}
	
	//加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request,ModelAndView mav){
    	
    }

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initInsOfflineFundDtlList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		InsOfflineFundDtlQueryCondition qc = new InsOfflineFundDtlQueryCondition();
		//TODO 设置查询条件？
		String applyLogId = request.getParameter("applyLogId");
		if (StringUtils.isNotEmpty(applyLogId)) {
			qc.setApplyLogId(Long.parseLong(applyLogId));
		}
		page.setCondition(qc);

		BaseLogUtils.info(logger, "initInsOfflineFundDtlList", "初始化InsOfflineFundDtl列表页面数据.DATA:"+JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		Pager pager = this.insOfflineFundDtlService.searchListPage(page);
		List<InsOfflineFundDtlVO> list = (List<InsOfflineFundDtlVO>) pager.getResultList();
		List<CapFundVO> capFundVOList = null;
		if (!CollectionUtils.isEmpty(list)) {
			CapFundQueryCondition condition = new CapFundQueryCondition();
			condition.setIdList(list.stream().map(InsOfflineFundDtlVO::getFundId).collect(Collectors.toList()));
			capFundVOList = capFundService.searchList(condition);
		}
		ListPageVO<CapFundVO> listPage = new ListPageVO<CapFundVO>(capFundVOList, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeInsOfflineFundDtlByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeInsOfflineFundDtlByIds", "删除InsOfflineFundDtl数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
		JSONArray idsArray = JSON.parseArray(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }
		
		try {
			boolean success = this.insOfflineFundDtlService.removeByIds(idsList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removeInsOfflineFundDtlByIds", "删除InsOfflineFundDtl数据失败,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removeInsOfflineFundDtlByIds", "删除InsOfflineFundDtl数据成功,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "removeInsOfflineFundDtlByIds", "删除InsOfflineFundDtl数据失败,ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeInsOfflineFundDtlByIds", "删除InsOfflineFundDtl数据失败,系统错误.ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getInsOfflineFundDtlById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getInsOfflineFundDtlById", "获取InsOfflineFundDtl数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			InsOfflineFundDtlVO vo = this.insOfflineFundDtlService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getInsOfflineFundDtlById", "获取InsOfflineFundDtl数据不存在,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getInsOfflineFundDtlById", "获取InsOfflineFundDtl数据成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "getInsOfflineFundDtlById", "获取InsOfflineFundDtl数据失败,ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getInsOfflineFundDtlById", "获取InsOfflineFundDtl数据失败,系统错误.ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addInsOfflineFundDtl(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		List<InsOfflineFundDtlVO> fundDtlVOList = null;//获取参数
		try {
			fundDtlVOList = this.getRequestParamForInsOfflineFundDtl(request);//获取参数
			Long applyLogId = fundDtlVOList.get(0).getApplyLogId();
			InsOfflineRepayLogVO repayLogVO = insOfflineRepayLogService.selectById(applyLogId);
			if (repayLogVO == null) {
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "线下还款申请不存在.");
			}

			McrBillMQC mcrBillMQC = new McrBillMQC();
			mcrBillMQC.setCrCntNo(repayLogVO.getCrCntNo());
			List<McrBillMDTO> mcrBillMDTOList = mcrBillMApiService.searchMcrBillMDTOList(mcrBillMQC);
			if (CollectionUtils.isEmpty(mcrBillMDTOList)) {
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "小贷账单不存在.");
			}
			McrBillMDTO mcrBillMDTO = mcrBillMDTOList.get(0);

			InsOfflineRepayDtlQueryCondition condition = new InsOfflineRepayDtlQueryCondition();
			condition.setApplyLogId(applyLogId);
			List<InsOfflineRepayDtlVO> repayDtlVOList = insOfflineRepayDtlService.searchList(condition);
			if (CollectionUtils.isEmpty(repayDtlVOList)) {
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "线下还款明细不存在.");
			}

			if (RepayConstant.LOAN_CHANNEL_LHYH.equals(mcrBillMDTO.getLoanChannel())) {
				String createTime = DateUtils.formatDateToString(repayLogVO.getCrtTm(), DateUtils.YYYY_MM_DD);
				String currentDate = DateUtils.getCurrentDateStr(DateUtils.YYYY_MM_DD);
				if (!createTime.equals(currentDate)) {
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "蓝海银行线下还款，请在提交申请当日绑定资金还款");
				}
			}

			this.insOfflineFundDtlService.batchAdd(fundDtlVOList);
			result.setData(applyLogId);
			BaseLogUtils.info(logger, "addInsOfflineFundDtl", "新增InsOfflineFundDtl数据成功,ID:"+applyLogId+".DATA:"+JSONObject.toJSONString(fundDtlVOList), CurrentThreadContext.getCurrentUserName());

			// 资金冻结
			List<CapFundVO> idsList = new ArrayList<CapFundVO>();
			CapFundVO entity = null;
			for (InsOfflineFundDtlVO fundDtlVO : fundDtlVOList) {
				entity = new CapFundVO();
				entity.setId(fundDtlVO.getFundId());
				entity.setFundStatusCd(CapitalConstant.CODE_CAP_FUND_STS_CD_9);//已冻结
				entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());//用户id
				idsList.add(entity);
			}
			//资金冻结
			boolean success = this.capFundService.ModifyListFundCstInfo(idsList);
			if (!success) {
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "冻结资金异常.");
			}



			if (mcrBillMDTO.getLoanChannel().equals(RepayConstant.LOAN_CHANNEL_YLYH)) {
				// 查询借据编号
				DataResultDTO dto = yiLlionApiService.queryAccLoanNoFromYL(repayLogVO.getCrCntNo());
				if (dto == null || dto.getSuccess() == 0 || dto.getData() == null) {
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "查询借据编号错误.");
				}
				String accLoanNo = (String) dto.getData();
				Map<String, Object> bizPara = new HashMap<>();
				if (repayLogVO.getRepayTypCd().equals(RepayConstant.REPAY_TYP_CD_PD)) {
					JSONArray jsonArray = new JSONArray();
					for (InsOfflineRepayDtlVO repayDtlVO : repayDtlVOList) {
						JSONObject jsonObject = new JSONObject();

						jsonObject.put("repayPeriod", repayDtlVO.getPayPd());
						jsonObject.put("repayAmt", repayDtlVO.getCapAmt() + repayDtlVO.getGrtAmt() + repayDtlVO.getIntrAmt()
								+ repayDtlVO.getOvdGrtAmt() + repayDtlVO.getPntAmt());
						jsonArray.add(jsonObject);
					}
					bizPara.put("payInfo", jsonArray);
				}
				if (repayLogVO.getRepayTypCd().equals(RepayConstant.REPAY_TYP_CD_SETTLE)) {
					// 查询还款明细，获取违约金
					InsOfflineRepayDtlVO repayDtlVO = repayDtlVOList.get(0);
					bizPara.put("penalAmt", repayDtlVO.getDamAmt());
				}

				bizPara.put("returnTime", repayLogVO.getCrtTm());
				bizPara.put("accLoanNo", accLoanNo);
				bizPara.put("custRepayDate", repayLogVO.getActPayDt());
				BaseLogUtils.info(logger, "addInsOfflineFundDtl", "cmmRechargeRecordApiService.offlineInsRepay.REQUEST: repayLogVO:" + JSON.toJSONString(repayLogVO) + ", bizPara:" + JSON.toJSONString(bizPara), CurrentThreadContext.getCurrentUserName());
				DataResultDTO resultDTO = cmmRechargeRecordApiService.offlineInsRepay(String.valueOf(repayLogVO.getId()), repayLogVO.getRepayAmt(), bizPara);
				BaseLogUtils.info(logger, "addInsOfflineFundDtl", "cmmRechargeRecordApiService.offlineInsRepay.RESPONSE:" + JSONObject.toJSONString(resultDTO), CurrentThreadContext.getCurrentUserName());
				if (resultDTO == null || resultDTO.getSuccess() == 0) {
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "亿联线下还款调用支付接口错误.");
				}
			}else if (StringUtils.isNotEmpty(mcrBillMDTO.getLoanChannel()) && mcrBillMDTO.getLoanChannel().equals(RepayConstant.LOAN_CHANNEL_LHYH)) {
				List<Long> capFundIdList = fundDtlVOList.stream().map(InsOfflineFundDtlVO::getFundId).collect(Collectors.toList());
				OfflineDecomposeParam requestParam = new OfflineDecomposeParam();
				requestParam.setCstId(mcrBillMDTO.getCstId());
				requestParam.setFundIdList(capFundIdList);
				requestParam.setRepayTypCd(repayLogVO.getRepayTypCd());
				requestParam.setBillId(repayLogVO.getBillId());
				requestParam.setRepayAmt(repayLogVO.getRepayAmt());
				requestParam.setRepayDt(repayLogVO.getActPayDt());
				requestParam.setTradeNo(repayLogVO.getId()+"");
				requestParam.setCrtUsrId(repayLogVO.getCrtUsrId());
				ResponseData responseData = capRepayCallbackApiService.offlineDecomposeLHYHBill(requestParam);
				InsOfflineRepayLogVO modifyRepayLogVO = new InsOfflineRepayLogVO();
				modifyRepayLogVO.setId(repayLogVO.getId());
				if (responseData == null || !responseData.isSuccess()) {
					modifyRepayLogVO.setApplyStsCd(RepayConstant.APPLY_STS_CD_3);
				} else {
					modifyRepayLogVO.setApplyStsCd(RepayConstant.APPLY_STS_CD_2);
				}
				boolean bool = insOfflineRepayLogService.modify(modifyRepayLogVO);
				if (!bool) {
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "更新线下还款申请状态异常.");
				}
			} else {
				InsOfflineRepayDtlVO offlineRepayDtlVO = repayDtlVOList.get(0);
				McrBillOfflineSettleDTO mcrBillOfflineSettleDTO = new McrBillOfflineSettleDTO();
				mcrBillOfflineSettleDTO.setApplyLogId(repayLogVO.getId());
				mcrBillOfflineSettleDTO.setCrCntNo(repayLogVO.getCrCntNo());
				mcrBillOfflineSettleDTO.setSettleDate(repayLogVO.getActPayDt());
				mcrBillOfflineSettleDTO.setSettlePayPd(offlineRepayDtlVO.getPayPd().intValue());
				mcrBillOfflineSettleDTO.setSettleCapAmt(offlineRepayDtlVO.getCapAmt());
				mcrBillOfflineSettleDTO.setSettleIntrAmt(offlineRepayDtlVO.getIntrAmt());
				mcrBillOfflineSettleDTO.setSettlePnlAmt(offlineRepayDtlVO.getPntAmt());
				mcrBillOfflineSettleDTO.setSettleDamAmt(offlineRepayDtlVO.getDamAmt());
				List<Long> capFundIdList = fundDtlVOList.stream().map(InsOfflineFundDtlVO::getFundId).collect(Collectors.toList());
				mcrBillOfflineSettleDTO.setCapFundId(capFundIdList);
				BaseLogUtils.info(logger, "addInsOfflineFundDtl", "mcrBillOfflineSettleApiService.decomposeBillOfflineSettle.REQUEST: mcrBillOfflineSettleDTO:" + JSON.toJSONString(mcrBillOfflineSettleDTO) , CurrentThreadContext.getCurrentUserName());
				DataResultDTO dataResultDTO = mcrBillOfflineSettleApiService.decomposeBillOfflineSettle(mcrBillOfflineSettleDTO);
				BaseLogUtils.info(logger, "addInsOfflineFundDtl", "mcrBillOfflineSettleApiService.decomposeBillOfflineSettle.RESPONSE: dataResultDTO:" + JSON.toJSONString(dataResultDTO) , CurrentThreadContext.getCurrentUserName());
				InsOfflineRepayLogVO modifyRepayLogVO = new InsOfflineRepayLogVO();
				modifyRepayLogVO.setId(repayLogVO.getId());
				if (dataResultDTO == null || dataResultDTO.getSuccess() == 0) {
					modifyRepayLogVO.setApplyStsCd(RepayConstant.APPLY_STS_CD_3);
				} else {
					modifyRepayLogVO.setApplyStsCd(RepayConstant.APPLY_STS_CD_2);
				}
				boolean bool = insOfflineRepayLogService.modify(modifyRepayLogVO);
				if (!bool) {
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "更新线下还款申请状态异常.");
				}
			}

			// 需要更新支付流水号  TODO
			// 等待支付提供
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "addInsOfflineFundDtl", "新增InsOfflineFundDtl数据失败.DATA:"+JSONObject.toJSONString(fundDtlVOList)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "addInsOfflineFundDtl", "新增InsOfflineFundDtl数据失败,系统错误.DATA:"+JSONObject.toJSONString(fundDtlVOList)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyInsOfflineFundDtl(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		InsOfflineFundDtlVO entity = null;
		try {
//			entity = //this.getRequestParamForInsOfflineFundDtl(request);
			if(entity.getId()==null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
				BaseLogUtils.info(logger, "modifyInsOfflineFundDtl", "修改InsOfflineFundDtl信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
				return result;
			}

			boolean success = this.insOfflineFundDtlService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modifyInsOfflineFundDtl", "修改InsOfflineFundDtl数据失败.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				return result;
			}
			BaseLogUtils.info(logger, "modifyInsOfflineFundDtl", "修改InsOfflineFundDtl数据成功.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "modifyInsOfflineFundDtl", "修改InsOfflineFundDtl数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "modifyInsOfflineFundDtl", "修改InsOfflineFundDtl数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	private List<InsOfflineFundDtlVO> getRequestParamForInsOfflineFundDtl(HttpServletRequest request) {
		String applyLogId = request.getParameter("applyLogId");//线下还款申请记录ID
		String capFunds = request.getParameter("capFunds");// 资金id
		if (StringUtils.isEmpty(applyLogId)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "还款申请不能为空.");
		}
		if (StringUtils.isBlank(capFunds)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "资金不能为空.");
		}
		// 资金
		List<InsOfflineFundDtlVO> fundDtlVOList = JSONObject.parseArray(capFunds, InsOfflineFundDtlVO.class);
		if (CollectionUtils.isEmpty(fundDtlVOList)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "资金信息错误.");
		}
		Date date = new Date();
		for (InsOfflineFundDtlVO insOfflineFundDtlVO : fundDtlVOList) {
			insOfflineFundDtlVO.setApplyLogId(Long.parseLong(applyLogId));
			insOfflineFundDtlVO.setCrtTm(date);
			insOfflineFundDtlVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
		}
		return fundDtlVOList;
	}
}

